package com.chief.tcc;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.chief.entity.Money;
import com.chief.mapper.MoneyMapper;
import com.chief.service.TccTestService;
import io.seata.rm.tcc.api.BusinessActionContext;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;

@DubboService
public class TccTestServiceImpl implements TccTestService {

    @Autowired
    private MoneyMapper moneyMapper;

    @Value("${a}")
    String name;

    @Override
    public boolean prepare(BusinessActionContext actionContext, Integer userId, BigDecimal money,Integer index) {
        System.out.println("aaaaaaaaaaaaaaa======="+name);
        if(index.compareTo(8)>=0){
            System.out.println(userId/0);
            return false;
        }
        Money byId = this.moneyMapper.selectById(userId);
        byId.setAmount(byId.getAmount().subtract(money));
        System.out.println("commitcommitcommitcommitcommitcommit"+byId.getAmount());
        this.moneyMapper.updateById(byId);
        return true;
    }

    @Override
    public boolean commit(BusinessActionContext actionContext) {
        System.out.println("commitcommitcommitcommitcommitcommit");
        return true;
    }

    @Override
    public boolean rollback(BusinessActionContext actionContext) {
        //得业务自行判断每部是否执行，最好使用状态位等机制
        Integer  userId = (Integer) actionContext.getActionContext("userId");
        BigDecimal money = (BigDecimal) actionContext.getActionContext("money");
        Money byId = this.moneyMapper.selectById(userId);
        System.out.println("rollbackrollbackrollbackrollbackrollbackrollback"+byId.getAmount());
        byId.setAmount(byId.getAmount().add(money));
        System.out.println("rollbackrollbackrollbackrollbackrollbackrollback"+byId.getAmount());
        this.moneyMapper.updateById(byId);
        return true;
    }

}
